/*
    异常相关的模块
*/

module.exports = {
    parseErrMsg(err){
        /*
            分析错误原因
        */
        let errMsg = "unknown"
        if(err && err.reason) {
            if( typeof err.reason == "string"){
                errMsg = err.reason
            }
            else if( typeof err.reason == "object" && err.reason.errMsg && typeof err.reason.errMsg == "string"){
                errMsg = err.reason.errMsg
            }
        }
        return errMsg
    },
    getReadableErrorMsg(msg) {
        /*
            错误信息优化
        */
        msg = msg || '未知错误';

        try {
            // 删除微信小程序框架底层堆栈日志
            msg = msg.split('\n').filter(
                line=>{
                    return (/.*WA\w*(Service|Context)\.js:2:/.test(line) === false)
                }
            ).join('\n');

            const knownErrors = [
                {
                    'reg': /.*(ERR_ADDRESS_UNREACHABLE|ERR_INTERNET_DISCONNECTED|MEDIA_ERR_NETWORK)$/,
                    'content': msg => {return '网络错误，请检查您手机网络是否正常'}
                },
                {
                    'reg': /.*(请求超时|timeout)$/,
                    'content': msg => {return '请求超时，请检查您手机网络是否正常'}
                },
                {
                    'reg': /.*502 Bad Gateway.*/,
                    'content': msg => {return '服务器异常，请稍后再试！'}
                },
                {
                    // navigateTo:fail page "pages/orders2/orders" is not found
                    'reg': /.*:fail page \"[\w\/]+\" is not found$/,
                    'content': msg => {
                        let page = msg.split('fail page ')[1].split(' ')[0];
                        return '页面不存在: ' + page.replace(/\"/g, '');
                    }
                }
            ]
            for (let i=0; i<knownErrors.length; ++i) {
                if (knownErrors[i].reg.test(msg)) {
                    msg = knownErrors[i].content(msg);
                    break;
                }
            }
        } catch (e) {
            getApp().mox.log.error(e);
        }

        return msg;
    },
    getIgnoreble(msg){
        /*
            判断异常是否可以忽略
        */
        let res = false;
        const skipedErrors = [
            /.*insertTextView:fail.*/,
            /.*updateTextView:fail.*/,
            /.*removeTextView:fail.*/,

            /.*insertImageView:fail.*/,
            /.*updateImageView:fail.*/,
            /.*removeImageView:fail.*/,

            /.*insertVideoPlayer:fail.*/,
            /.*updateVideoPlayer:fail.*/,
            /.*updateVideoPlayer:fail.*/,
            /.*toast can't be found.*/,
            /.*showLoading.*/,
            /.*navigateBack:fail cannot navigate back at first page.*/,
        ]

        skipedErrors.forEach( regex => {
            if(regex.test(msg)){
                res = true
            }
        })
        return res;
    }
}